package com.cloudfun.campusshare.configuration.jpa.specification;


import com.cloudfun.campusshare.configuration.jpa.util.JpaRestrictionBuilder;
import com.cloudfun.campusshare.configuration.jpa.util.PropertyFilter;
import org.springframework.data.jpa.domain.Specification;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 王溪源
 * @ClassName: PropertyFilterSpecification
 * @Description: TODO
 **/
public class PropertyFilterSpecification<T> implements Specification<T> {
    private List<PropertyFilter> filters = new ArrayList<> ();

    public PropertyFilterSpecification(PropertyFilter propertyFilter) {
        this.filters.add (propertyFilter);
    }

    public PropertyFilterSpecification(List<PropertyFilter> filters) {
        this.filters.addAll (filters);
    }

    @Override
    public Predicate toPredicate(Root<T> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
        List<Predicate> list = new ArrayList<> ();
        for (PropertyFilter filter : filters) {
            list.add (JpaRestrictionBuilder.getRestriction (filter, new SpecificationModel (root, criteriaQuery, criteriaBuilder)));
        }
        return list.size () > 0 ? criteriaBuilder.and (list.toArray (new Predicate[list.size ()])) : null;
    }

    public List<PropertyFilter> getFilters() {
        return filters;
    }

    public void setFilters(List<PropertyFilter> filters) {
        this.filters = filters;
    }
}
